// components/editFreeAmountModal/edit-freeAmo-Modal.js
const utils = require('../../utils/util.js')
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    isShowModal: { type: Boolean, value: false},
    dataModal: Object,
    originalBalance: {type: Number, value: 0}
  },

  /**
   * 组件的初始数据
   */
  data: {
    isShowModal: false,
    originalBalance: 0,
    inputAmountIsOnlyReady: false
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**关闭模态框事件 */
    modalCancel: function(){
      this.setData({ isShowModal: false })
    },
    /**模态框确定按钮 */
    modalConfirm: function(e){
      if(this.data.inputAmountIsOnlyReady){
        this.modalCancel()
        return;
      }
      const that = this
      const dataModal = this.data.dataModal
      const freeAmount = Number(dataModal.freeAmount)
      const balance = Number(dataModal.balance)
      const nativeFreeBalance = Number(balance - freeAmount).toFixed(2)
      const plus = balance.toFixed(2) - freeAmount.toFixed(2)
      console.log('balance:',balance.toFixed(2),'freeAmount: ',freeAmount.toFixed(2),'plus: ',plus,'nativeFreeBalance: ',nativeFreeBalance)
      if(plus.toFixed(2) != nativeFreeBalance){
        wx.showToast({ title: '金额错误',icon: 'icon-box-img',duration: 2000})
        return ;
      }
      //更新数据库
      wx.cloud.callFunction({
        // 云函数名称
        name: 'updateCollectionById',
        // 传给云函数的参数
        data: {_id: dataModal._id, freeAmount: freeAmount.toFixed(2), reqType: 'updateAmountById', collectionName: 'freeCaptiveDetails' },
        //数据库更新成功则更新本地数据
        success: function(res) {
          console.log('请求云函数后返回的结果(res): ',res) // 3
          if(res.result.stats.updated == 1){
            that.triggerEvent('refreshModal', e, {})
          }
        },
        fail: error => {
          wx.showToast({title:"更新失败",icon: "icon-box-img",duration: 2000})
        }
      })
      //提交后更新数据库，而后更新本地数据
      this.modalCancel()
    },
    /**模态框金额改变时触发 */
    changeHandle: function(e){
      const originalBalance = this.data.originalBalance
      let value = e.detail.value
      const reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9][0-9]$)/;
      if(!reg.test(value)){
        value = value.replace(/[^\d\.]/g, ""); //清除"数字"和"."以外的字符
        value = value.replace(/^\./g, ""); //验证第一个字符是数字
        value = value.replace(/\.{2,}/g, "."); //只保留第一个, 清除多余的
        value = value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
        value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
        value = value.replace(/(?!^[0]\.)^[0]/,"") //开头不等于“0.”且首位为0则替换，表达式且：(?=表达式A)表达式B，同时满足A和B
      }
      const plus = Number(originalBalance - Number(value)).toFixed(2)
      console.log(plus)
      //放生额大于余额时，放生额等于余额,放生额为0
      if(plus < 0){
        this.setData({ 'dataModal.freeAmount': originalBalance,'dataModal.nativeFreeBalance': 0 })
        wx.showToast({ title: '输入额度太大', icon: 'icon-box-img', duration: 2000})
        return ;
      }
      this.setData({'dataModal.freeAmount': value, 'dataModal.nativeFreeBalance': Number(plus).toFixed(2)})
    },
  },
  observers:{
    "isShowModal": async function(isShowModal){
      if(isShowModal){
        const freeAmount = Number(this.data.dataModal.freeAmount)
        const balance = Number(this.data.dataModal.balance)
        const sum = freeAmount + balance
        this.setData({originalBalance:  sum.toFixed(2)})
        //设置金额输入框是否只读
        const todayDate = await utils.formatDateOrTime(new Date(),"yyyy-MM-dd")
        const freeDate = this.data.dataModal.freeDate
        console.log('今日日期：',todayDate,'显示日期：',freeDate,"金额输入框是否只读：",this.data.inputAmountIsOnlyReady)
        if(todayDate != freeDate){
          this.setData({inputAmountIsOnlyReady: true})
        }
      }
    }
  }
})
